package com.ibpd.shopping.service.account;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.ibpd.dao.impl.BaseServiceImpl;
import com.ibpd.dao.impl.HqlParameter;
import com.ibpd.henuocms.common.MD5;
import com.ibpd.shopping.entity.AccountEntity;
@Service("accountService")
public class AccountServiceImpl extends BaseServiceImpl<AccountEntity> implements IAccountService {
	public AccountServiceImpl(){
		super();
		this.tableName="AccountEntity";
		this.currentClass=AccountEntity.class;
		this.initOK();
	}

	public Boolean checkAccountExist(String account) {
		return checkValueExist("account",account);
	}

	public Boolean checkEmailExist(String email) {
		return checkValueExist("email",email);
	}

	public Boolean checkNicknameExist(String nickname) {
		return checkValueExist("account",nickname);
	}
	private Boolean checkValueExist(String field,String value){
		String whereStr="from "+this.getTableName()+" where ${field}='"+value+"'";
		whereStr=whereStr.replace("${field}", field);
		List<AccountEntity> accList=this.getList(whereStr, null);
		if(accList!=null && accList.size()>0){
			return true;
		}
		return false;
	}

	public AccountEntity getAccountByAccount(String account) {
		if(StringUtils.isBlank(account))
			return null;
		List<HqlParameter> hqlList=new ArrayList<HqlParameter>();
		hqlList.add(new HqlParameter("account",account,HqlParameter.DataType_Enum.String));
		List<AccountEntity> accList=this.getList("from "+this.getTableName()+" where account=:account", hqlList);
		if(accList!=null && accList.size()>0)
			return accList.get(0);
		else
			return null;
	}

	public AccountEntity getAccountByEmail(String email) {
		if(StringUtils.isBlank(email))
			return null;
		List<HqlParameter> hqlList=new ArrayList<HqlParameter>();
		hqlList.add(new HqlParameter("email",email,HqlParameter.DataType_Enum.String));
		List<AccountEntity> accList=this.getList("from "+this.getTableName()+" where email=:email", hqlList);
		if(accList!=null && accList.size()>0)
			return accList.get(0);
		else
			return null;
	}

	public void initTestAccount() {
		for(Integer i=0;i<10;i++){
			AccountEntity acc=new AccountEntity();
			acc.setAccount("test"+i);
			acc.setNickname("测试用户"+i);
			acc.setPassword(MD5.md5("123456"));
			acc.setEmail("testuser"+i+"@qq.com");
			acc.setEmailIsActive("y");
			this.saveEntity(acc);
		}
		
		
	}

	@Override
	public int saveEntity(AccountEntity entity) {
		entity.setDiffAreaLogin("");
		entity.setFreeze(AccountEntity.RESSZ_PASSED);
		entity.setFreezeEnddate(new Date());
		entity.setFreezeStartdate(new Date());
		entity.setLastLoginTime(new Date());
//		entity.setPassword(MD5.md5(entity.getPassword()));
		entity.setRegeistDate((entity.getRegeistDate()!=null)?entity.getRegeistDate():new Date());
		return super.saveEntity(entity);
	}
}
